package org.example.gateway.config;

import org.example.gateway.handler.RequestAccessDeniedHandler;
import org.example.gateway.handler.RequestAuthenticationEntryPoint;
import org.example.gateway.config.properties.IgnoreWhiteProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.SecurityWebFiltersOrder;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.oauth2.server.resource.web.server.ServerBearerTokenAuthenticationConverter;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.authentication.AuthenticationWebFilter;

/**
 * security相关配置类
 */
@Configuration
@EnableWebFluxSecurity
public class SecurityConfiguration {


    @Autowired
    private JwtAccessManager jwtAccessManager;
    @Autowired
    private JwtAuthenticationManager jwtAuthenticationManager;
    @Autowired
    private RequestAccessDeniedHandler requestAccessDeniedHandler;
    @Autowired
    private RequestAuthenticationEntryPoint requestAuthenticationEntryPoint;
    @Autowired
    private IgnoreWhiteProperties ignoreWhiteProperties;
    @Bean
   public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity httpSecurity){
        AuthenticationWebFilter authenticationWebFilter=new AuthenticationWebFilter(jwtAuthenticationManager);
        authenticationWebFilter.setServerAuthenticationConverter(new ServerBearerTokenAuthenticationConverter());
        String[]  urls=new String[ignoreWhiteProperties.getWhites().size()];
        ignoreWhiteProperties.getWhites().toArray(urls);
        httpSecurity
                 .httpBasic().disable()
                .csrf().disable()
                .authorizeExchange()
                .pathMatchers(urls).permitAll()
                .anyExchange()
                .access (jwtAccessManager)
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(requestAuthenticationEntryPoint)
                .accessDeniedHandler (requestAccessDeniedHandler)
                .and()
//                .addFilterAt((WebFilter) corsFilter,SecurityWebFiltersOrder.CORS)
                .addFilterAt(authenticationWebFilter, SecurityWebFiltersOrder.AUTHENTICATION)
        ;
         return httpSecurity.build();
    }


}
